#include "MW_WebEngineView.h"
#include "ui_MW_WebEngineView.h"

#include <QWebEngineProfile>
#include <Windows.h>
#pragma comment ( lib, "user32.lib" )

#include "EncryptionZ.h"

QString g_strHashKey = "aB6#8NhJ)97BfdPlmkVcz";

MW_WebEngineView::MW_WebEngineView(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MW_WebEngineView),
    searchShop(this, &FweView, "龟")
{
    ui->setupUi(this);

    FdtPercent100 = QDateTime::currentDateTime();
    FbShow_WebEngineView = false;

    QObject::connect(FweView.page(), &QWebEnginePage::loadStarted,  this, &MW_WebEngineView::WEP_LoadStarted);
    QObject::connect(FweView.page(), &QWebEnginePage::loadProgress, this, &MW_WebEngineView::WEP_LoadProgress);
    QObject::connect(FweView.page(), &QWebEnginePage::loadFinished, this, &MW_WebEngineView::WEP_LoadFinished);
    //QObject::connect(FweView.page(), &QWebEnginePage::scrollPositionChanged, this, &MW_WebEngineView::WEP_ScrollPositionChanged);
    QObject::connect(FweView.page(), &QWebEnginePage::urlChanged, this, &MW_WebEngineView::WEP_UrlChanged);

//    QObject::connect(FweView.page(), &QWebEnginePage::loadFinished, this, &MW_WebEngineView::WEP_LoadFinished);
//    QWebEngineProfile::defaultProfile()::QWebEngineCookieStore::cookieAdded()
//    QWebEngineProfile.defaultProfile().cookieStore().cookieAdded.connect(self.onCookieAdd)
    connect(FweView.page()->profile()->cookieStore(), &QWebEngineCookieStore::cookieAdded,
            this, &MW_WebEngineView::CookieAdded);

}

MW_WebEngineView::~MW_WebEngineView()
{
    FweView.close();
    delete ui;
}

void MW_WebEngineView::on_pbtnOpenURL_clicked()
{
    QString str = ui->ledtUrl->text().trimmed();
    if (str.isEmpty())
    {
        QMessageBox::information(NULL, "请输入URL", "URL为空", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
        return;
    }

//    if (!FhashCookie.isEmpty())
//    {
//        QWebEngineCookieStore* pCookieStore = FweView.page()->profile()->cookieStore();
//        for (QHash<QString, QString>::iterator it = FhashCookie.begin(); it != FhashCookie.end(); ++it)
//        {
//            QNetworkCookie cookie(it.key().toUtf8(), it.value().toUtf8());
//            cookie.setDomain(".taobao.com");
//            cookie.setPath("/");

//            pCookieStore->setCookie(cookie);
//        }
//        AddMsg("设置cookie：共"+QString::number(FhashCookie.count())+"组信息. \r\n");
//    }
    //uc1=cookie15=VT5L2FSpMGV7TQ%3D%3D&pas=0&existShop=false&cookie16=URm48syIJ1yk0MX2J7mAAEhTuw%3D%3D&cookie21=WqG3DMC9Fb5mPLIQoVXj&cookie14=UoTV7N%2B%2FUxPWDg%3D%3D; Domain=.taobao.com; Path=/
    //uc1=cookie15=VT5L2FSpMGV7TQ%3D%3D
    //pas=0
    //existShop=false
    //cookie16=URm48syIJ1yk0MX2J7mAAEhTuw%3D%3D
    //cookie21=WqG3DMC9Fb5mPLIQoVXj
    //cookie14=UoTV7N%2B%2FUxPWDg%3D%3D
    //; Domain=.taobao.com; Path=/

//    FhashCookie.clear();
//    {
//        FhashCookie.insert("uc1", "VT5L2FSpMGV7TQ%3D%3D");
//        FhashCookie.insert("cookie15", "VT5L2FSpMGV7TQ%3D%3D");
//        FhashCookie.insert("pas", "0");
//        FhashCookie.insert("cookie16", "URm48syIJ1yk0MX2J7mAAEhTuw%3D%3D");
//        FhashCookie.insert("cookie21", "WqG3DMC9Fb5mPLIQoVXj");
//        FhashCookie.insert("cookie14", "UoTV7N%2B%2FUxPWDg%3D%3D");
//        FhashCookie.insert("existShop", "false");
//        //FhashCookie.insert("", "");

//        QWebEngineCookieStore* pCookieStore = FweView.page()->profile()->cookieStore();
//        for (QHash<QString, QString>::iterator it = FhashCookie.begin(); it != FhashCookie.end(); ++it)
//        {
//            QNetworkCookie cookie(it.key().toUtf8(), it.value().toUtf8());
//            cookie.setDomain(".taobao.com");
//            cookie.setPath("/");

//            pCookieStore->setCookie(cookie);
//        }
//    }

    FbShow_WebEngineView = true;

    //FweView.setUrl(QUrl("https://login.taobao.com/member/login.jhtml"));
//    FweView.setUrl(QUrl(str));

    searchShop.Request(tbrtLogin);
    FweView.show();

    QRect rtThis = this->geometry();
    QRect rtWEV = FweView.geometry();
    FweView.setGeometry(rtThis.left()+50, rtThis.top()+50, rtWEV.width(), rtWEV.height());

    AddMsg("打开网页(时间): \t"+TimeStr(tstDateTimeMillisecond, &FdtUrlSet));
}

void MW_WebEngineView::on_pbtnShowHideWEV_clicked()
{
    //FweView.show();

//    qDebug() << "FbShow_WebEngineView: "<< FbShow_WebEngineView;
//    if (FbShow_WebEngineView)
//        FweView.hide();
//    else
//        FweView.show();
//    FbShow_WebEngineView = ! FbShow_WebEngineView;

    // ZC: 上面的方式，FweView 会显示不出来... 不知道为啥...???
    if (FbShow_WebEngineView)
        ShowWindow((HWND)FweView.winId(), SW_HIDE);
    else
        ShowWindow((HWND)FweView.winId(), SW_SHOW);
    FbShow_WebEngineView = ! FbShow_WebEngineView;

}

void MW_WebEngineView::on_pbtnXlhCookie_clicked()
{
    QFile file(QCoreApplication::applicationDirPath() + "/cookie_taobao.txt");
    if(!file.open(QIODevice::WriteOnly))
    {
        qDebug() << "can't open file for write";
        return;
    }

    QDataStream out(&file);
    out << FhashCookie;

    AddMsg("保存cookie至本地硬盘：共"+QString::number(FhashCookie.count())+"组信息. "+file.fileName());
}

void MW_WebEngineView::on_pbtnFxlhCookie_clicked()
{
    FhashCookie.clear();

    QFile file(QCoreApplication::applicationDirPath() + "/cookie_taobao.txt");
    if(!file.open(QIODevice::ReadOnly))
    {
        qDebug() << "can't open file for read";
        return;
    }

    QDataStream in(&file);
    in >> FhashCookie;

    AddMsg("读取cookie从本地硬盘：共"+QString::number(FhashCookie.count())+"组信息. "+file.fileName());
    int iIdx = 0;
    for (QHash<QString, QString>::iterator it=FhashCookie.begin(); it!=FhashCookie.end(); ++it)
    {
        AddMsg("["+QString::number(iIdx)+"] -- "+ it.key()+" :");
        AddMsg(it.value());
    }
    AddMsg("");
}

void MW_WebEngineView::on_pbtnRefresh_clicked()
{
    FweView.reload();
}

void MW_WebEngineView::on_pbtnClearMsg_clicked()
{
    ui->tedtMsg->clear();
}

// ***

void MW_WebEngineView::SetURL(QString _strURL)
{
    ui->ledtUrl->setText(_strURL);
}

void MW_WebEngineView::SetINI(QString _strINI)
{
    FstrIniFile = _strINI;

    searchShop.SetExtendInfo(FstrIniFile);
}

void MW_WebEngineView::AddMsg(QString _str)
{
    ui->tedtMsg->append(_str);
}

void MW_WebEngineView::Ini_JieMi(QString _strIniFile, QString _strNodeName, QString _strKeyName, QString *_pstrOut)
{
    QSettings set(_strIniFile, QSettings::IniFormat);

    QVariant qvar = set.value(QString("/%1/%2").arg(_strNodeName).arg(_strKeyName));
    QString strMiWen = qvar.toString();
    //qDebug() << strMingWen;

    JieMi(g_strHashKey, strMiWen, _pstrOut);// 密文 明文
}

QString MW_WebEngineView::TimeStr(ETimeStrType tst, QDateTime* _pTime)
{
    QDateTime time = QDateTime::currentDateTime();//获取系统现在的时间
    if (tst == tstDateTimeMillisecond)
    {
        if (_pTime != NULL) *_pTime = time;
        return time.toString("yyyy-MM-dd hh:mm:ss.zzz"); //设置显示格式
    }
    else if (tst == tstTimeMillisecond)
    {
        if (_pTime != NULL) *_pTime = time;
        return time.toString("hh:mm:ss.zzz");
    }
    else
        return NULL;
}

        class ScriptCallback
        {
        public:
            static MW_WebEngineView *mv;// = NULL;

            void operator()(const QVariant &result)
            {
                mv->AddMsg(result.toString());
            }
        };
        MW_WebEngineView* ScriptCallback::mv = NULL;

void MW_WebEngineView::Timer_Timeout()
{
    //QWebEnginePage* pPage = FweView.page();
    AddMsg("timerJS - Timeout(...) --> " + FweView.url().url());

    searchShop.Response();
}

//  ***  ***  ***  ***  ***  ***  ***  ***  ***  ***  ***  ***  ***  ***  ***  ***  ***  ***  ***  ***

void MW_WebEngineView::WEP_LoadStarted()
{
    AddMsg("网页加载开始(时间): \t"+TimeStr(tstDateTimeMillisecond, &FdtUrlLoadStart));
}

void MW_WebEngineView::WEP_LoadProgress(int progress)
{
    AddMsg("网页加载中(时间): \t"+TimeStr(tstDateTimeMillisecond, NULL)+"; 百分比: "+QString::number(progress)+"%");

    if (progress != 100)
        return;

    AddMsg("网页加载 100% -- URL: " + FweView.url().url());

    QDateTime dtNow = QDateTime::currentDateTime();
    qint64 int64Pass = FdtPercent100.msecsTo(dtNow);
    FdtPercent100 = dtNow;
    if (int64Pass < 500)
        return;

    int iTimeWait = searchShop.IfResponse_byType(wrtProcessPercent100);
    if (iTimeWait >= 0)
    {
        if (iTimeWait == 0)
            Timer_Timeout();
        else
            QTimer::singleShot(iTimeWait, this, &MW_WebEngineView::Timer_Timeout);
    }
}

void MW_WebEngineView::WEP_LoadFinished(bool _ok)
{
    AddMsg("网页加载完成(时间): \t"+TimeStr(tstDateTimeMillisecond, &FdtUrlLoadFinished));
    if (_ok)
        AddMsg("网页加载完成(状态): true");
    else
        AddMsg("网页加载完成(状态): false");
    AddMsg("网页加载耗时(秒)(打开网页-->加载完成): " + QString::number(FdtUrlSet.secsTo(FdtUrlLoadFinished)));
    AddMsg("网页加载耗时(秒)(开始加载-->加载完成): " + QString::number(FdtUrlLoadStart.secsTo(FdtUrlLoadFinished)));

    int iTimeWait = searchShop.IfResponse_byType(wrtLoadFinished);
    if (iTimeWait >= 0)
    {
        if (iTimeWait == 0)
            Timer_Timeout();
        else
            QTimer::singleShot(iTimeWait, this, &MW_WebEngineView::Timer_Timeout);
    }
}

void MW_WebEngineView::WEP_ScrollPositionChanged(const QPointF &position)
{
    AddMsg("网页滚动条位置改变 -- x: "+QString::number(position.x())+", y: "+QString::number(position.y()));
}

void MW_WebEngineView::WEP_UrlChanged(const QUrl &url)
{
    AddMsg("URL改变了: " + url.url());
}

void MW_WebEngineView::CookieAdded(const QNetworkCookie &cookie)
{
    Q_UNUSED(cookie)

//    QString name = QString::fromUtf8(cookie.name().data());
//    QString value = QString::fromUtf8(cookie.value().data());
//    qDebug() << "Cookie name : "<<name;
//    qDebug() << "Cookie value : "<<value;
//    FhashCookie.insert(name, value);

    //QString name = cookie.name().data().decode('utf-8');//     # 先获取cookie的名字，再把编码处理一下
    //QString value = cookie.value().data().decode('utf-8');//   # 先获取cookie值，再把编码处理一下
}


